<template>
    <div>
        <van-row class="correction-title" type="flex" align="center">
            <van-col span="16"> <i class="iconfont icon-yuanzhu L-title" style="color:#409EFF"></i><span
                    class="L-text">数据纠错</span></van-col>
            <van-col span="8" style="text-align: right;">
                <van-button type="primary" size="small" @click="handleAdd"> + 添加一行</van-button>
                <!-- <span class="L-small-text">添加一行</span> -->
            </van-col>
        </van-row>

        <ErrorCorrectionFormInput v-for="(item, index) in errorCorrectionArr" :key="index" :formItem="item"
            :formItemIndex="index" :handleSelectField="handleSelectField"
            :handleDeleteCorrectionField="handleDeleteCorrectionField" :handleChange="handleChange">
        </ErrorCorrectionFormInput>

        <div class="L-bottom-space"></div>
        <van-sticky position="bottom">
            <div class="L-bottom-row">
                <div class="L-operate-btn" @click="callBack()">取消</div>
                <div class="L-operate-btn" @click="handleSave()">保存</div>
            </div>
        </van-sticky>
        <van-divider />

        <van-row class="correction-title" type="flex" align="center">
            <van-col span="16"> <i class="iconfont icon-yuanzhu L-title" style="color:#409EFF"></i><span
                    class="L-text">上传图片</span></van-col>
        </van-row>
        <div style="padding:10px 15px">
            <van-uploader v-model="uploadList" multiple :after-read="handleUpload" accept="*">
                <template #preview-cover="{ file }">
                    <!-- <div class="preview-cover van-ellipsis" @click.stop="handleDownload(file.name)">下载文件</div> -->
                </template>
            </van-uploader>

        </div>


        <van-popup v-model:show="showPicker" position="bottom">
            <van-picker title="选择字段" :columns="columns" @confirm="handleFieldConfirm" />
        </van-popup>








    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue"
import { showLoadingToast, closeToast, showToast } from "vant"
import { apiConfigurable, } from "@/request/api/api"

import ErrorCorrectionFormInput from "@/components/base/ErrorCorrection/ErrorCorrectionFormInput.vue";

const props = defineProps({

    itemid: {
        type: String,
        default: ""
    },
    idobject: {
        type: String,
        default: ""
    },
    callBack: {
        type: Function,
        default: () => { }
    },

})

onMounted(() => {
    getData()
})

const detailsArr = ref([])

const columns = computed(() => {
    const res = []

    for (let i = 0; i < detailsArr.value.length; i++) {
        let groupvalue = detailsArr.value[i].groupvalue
        for (let j = 0; j < groupvalue.length; j++) {
            let filedItem = groupvalue[j]
            res.push({ text: filedItem.sTitle, value: filedItem.sTitle, })
        }
    }
    return res

})

const uploadList = ref([])



const showPicker = ref(false)

interface fieldVO {
    [idx: string]: any;
}

const errorCorrectionArr = ref<fieldVO[]>([
    {}
])


const isLoading = ref(false)

function getData() {
    isLoading.value = true;
    showLoadingToast({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
    });

    const { idobject, itemid } = props
    const url = `${idobject}.edit.do`
    const data = {
        [`${idobject}_id`]: itemid
    }

    apiConfigurable(url, data, "post").then((res) => {
        if (res.code === 0) {
            isLoading.value = false;

            detailsArr.value = res.data.jsondata?.head;
            //   object_id.value = res.data.jsondata[`${props.idobject}_id`] || ""     

            closeToast();

        } else {
            setTimeout(() => {

            }, 1000)

        }

    }
    );
}

function handleSelectErrorCorrectionField(sTitle) {

    let res = []
    loop: for (let i = 0; i < detailsArr.value.length; i++) {
        let groupvalue = detailsArr.value[i].groupvalue
        for (let j = 0; j < groupvalue.length; j++) {
            let filedItem = groupvalue[j]
            if (sTitle === filedItem.sTitle) {
                errorCorrectionArr.value[currentIndex] = {}
                Object.keys(filedItem).forEach(key => {
                    errorCorrectionArr.value[currentIndex][key] = filedItem[key]
                })
                break loop
            } else {
                continue
            }
        }
    }


}

// 删除纠错数据
function handleDeleteCorrectionField(index) {
    errorCorrectionArr.value.splice(index, 1)
}

let currentIndex = 0
//选择纠错字段
function handleSelectField(index) {
    currentIndex = index
    showPicker.value = true
}

function handleAdd() {
    errorCorrectionArr.value.push({})
}
function handleChange(item, value, valuehidden = "") {
    item.value = value
    if (valuehidden) {
        item.valuehidden = valuehidden

    }
}

function checkData(data){
 

    if(data.some(item=>{return !item.sField})){
        showToast("请检查字段")
        return false
    }

    return true

}

function handleSave() {
    const { itemid } = props
    if(!checkData(errorCorrectionArr.value)){
        return
    }

    // return 
    
    const data = {}
    for (let i = 0; i < errorCorrectionArr.value.length; i++) {
        const item = errorCorrectionArr.value[i]
        data[`${i}_datacorrect_correctfield`] = item.sField//纠错字段
        data[`${i}_datacorrect_sname`] = getOldValue(item.sField)//旧值
        data[`${i}_datacorrect_correctname`] = item.sTitle//纠错字段名
        data[`${i}_datacorrect_source`] = sessionStorage.getItem("username") || ''//来源(当前登录用户)
        data[`${i}_datacorrect_idclientall`] = itemid//客户大全(id)
        data[`${i}_datacorrect_correctvalue`] = item.value//纠错值(新值)
        data[`${i}_datacorrect_correctkey`] = item.valuehidden//纠错值(id)
        data[`${i}_datacorrect_snote`] = '由用户创建纠错'//备注
        data[`${i}_datacorrect_jcdz`] = '2c9a2d9293fc56db0193fc59e1290041'//纠错值(id)
        data[`${i}_datacorrect_img`] = newNameStr.value
        data[`${i}_datacorrect_img_title`] = oldNameStr.value

    }


    showLoadingToast({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "上传中...",
    });




    const api = "datacorrect.newmultirowsave.do"

    apiConfigurable(api, data).then((res) => {
        if (res.code === 0) {
            showToast("提交成功")
            setTimeout(() => {
                props.callBack()
            }, 1000)

        }

    });



}

function getOldValue(field) {

    for (let i = 0; i < detailsArr.value.length; i++) {
        let groupvalue = detailsArr.value[i].groupvalue
        for (let j = 0; j < groupvalue.length; j++) {
            let filedItem = groupvalue[j]
            if (field === filedItem.sField) {
                return filedItem.value

            } else {
                continue
            }
        }
    }

}

function handleFieldConfirm({ selectedOptions }) {
    // console.log(selectedOptions[0].value)
    handleSelectErrorCorrectionField(selectedOptions[0].value)
    showPicker.value = false
}

function handleFieldChange({ selectedOptions }) {
    console.log(selectedOptions)
}


const oldNameStr = ref("")
const newNameStr = ref("")

function handleUpload(file) {

    let deviceFile = [];
    let formData = new FormData();
    if (Array.isArray(file)) {
        deviceFile = file;
    } else {
        deviceFile.push(file);
    }

    for (let i = 0; i < deviceFile.length; i++) {
        formData.append("file" + i, deviceFile[i].file, deviceFile[i].name);
    }
    showLoadingToast({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "上传中...",
    });



    //   const api = sUIType === "picture" ? "upload.imagedo" : "upload.filedo";
    const api = "upload.imagedo"

    apiConfigurable(api, formData).then((res) => {
        if (res.code === 0) {
            closeToast();
            //   itemValue.value = res.data[0].oldname;
            //   itemId.value = res.data[0].newname;

            oldNameStr.value += res.data[0].oldname + ";"
            newNameStr.value += res.data[0].newname + ";"
        }

    });
}



function handleDownload(filename) {
    const index = oldNameStr.value.split(";").indexOf(filename)
    const newname = newNameStr.value.split(";")[index]


    if (newname) {
        const url = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "/");
        window.location.href = `${url}/userfile/default/attach/${newname}`
    }
}



</script>

<style scoped>
.correction-title {
    /* text-align: center; */
    margin: 20px auto;
    box-sizing: border-box;
    padding-left: 10px;
    padding-right: 10px;
}
</style>